const CryptoJS = require('crypto-js')

function getAesString(n, f, c) {
  f = f.replace(/(^\s+)|(\s+$)/g, '')
  f = CryptoJS.enc.Utf8.parse(f)
  c = CryptoJS.enc.Utf8.parse(c)
  return CryptoJS.AES.encrypt(n, f, {
    iv: c,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  }).toString()
}
function encryptAES(n, f) {
  // eslint-disable-next-line no-use-before-define
  return f ? getAesString(randomString(64) + n, f, randomString(16)) : n
}
function encryptPassword(n, f) {
  try {
    return encryptAES(n, f)
  } catch (c) {
    return c
  }
}
const $aesChars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
const aesCharsLen = $aesChars.length
function randomString(n) {
  let f = ''
  for (let i = 0; i < n; i++)
  { f += $aesChars.charAt(Math.floor(Math.random() * aesCharsLen)) }
  return f
}
module.exports = {
  encryptPassword,
  randomString,
}
